package com.htfyun.factorytest.engineerui;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.lang.ref.WeakReference;


import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.htfyun.factorytest.ViewDialogFragment;
import com.htfyun.factorytest.common.FTUtils;
import com.htfyun.factorytest.common.PermissionManager;
import com.htfyun.factorytest.myrecorder.RecorderOperator;
import com.htfyun.factorytest.playerutils.MediaPlayerTool;

import com.htfyun.factorytest.R;

public class RecorderActivity extends Activity implements View.OnClickListener {

    private final String TAG = "RecorderActivity";
    private static final String RECORDER_FILE_PATH = FTUtils.getFTStorageDirectory() + File.separator + "record_test.pcm";
    private static final int RECORD_MIN_TIME = 5 * 1000;

    private Context mContext;

    private boolean isRecording = false;

    private Button start_record;
    private Button stop_record;
    private Button play_record;
    private Button finish_record;


    private AudioManager mAudioManager;

    private TextView txtDesc;
    private TextView record_status;
    private boolean isPcba;

    private MyHandler myHandler;
    private MediaPlayerTool mediaPlayerTool;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //保持屏幕常亮
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        setContentView(R.layout.activity_recorder);
        mContext = this;
        myHandler = new MyHandler(this);
        mediaPlayerTool = MediaPlayerTool.getInstance(mContext, myHandler);

        txtDesc = (TextView) findViewById(R.id.txtDesc);
        record_status = (TextView) findViewById(R.id.record_status);

        //从intent得到一个boolean值，如果这个值为true则让txtDesc显示
        isPcba = getIntent().getBooleanExtra("isPcba", false);
        if (isPcba) {
            txtDesc.setVisibility(View.INVISIBLE);
        }

        //绑定按钮点击事件
        start_record = (Button) findViewById(R.id.start_record);
        start_record.setOnClickListener(this);
        stop_record = (Button) findViewById(R.id.stop_record);
        stop_record.setOnClickListener(this);

        play_record = (Button)findViewById(R.id.play_record);
        play_record.setOnClickListener(this);

        finish_record = (Button) findViewById(R.id.finish_record);
        finish_record.setOnClickListener(this);

        start_record.setEnabled(true);
        stop_record.setEnabled(false);
        play_record.setEnabled(false);
        finish_record.setEnabled(false);

        //动态权限申请，申请录音和写外部存储权限
        initPermission();

    }


    @Override
    protected void onResume() {
        super.onResume();

        //检查是否插入耳机
        AudioManager audioManager = (AudioManager) getSystemService(AudioManager.class);
        if (!audioManager.isWiredHeadsetOn()) {
            //如果耳机未插入，弹窗未检测到耳机插入
            showDialogWhenHeadsetUnplug();
        }

        //发送广播检测耳机插入状态
        IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
        registerReceiver(headsetPlugReceiver, filter);

    }

    @Override
    protected void onPause() {
        super.onPause();
        //注销广播接收器
        unregisterReceiver(headsetPlugReceiver);
        stopRecord();
    }

    private void initPermission() {
        //如果无权限就申请然后回调，如果有权限就执行录音监听
        if (!isRecordGotPermission()) {

            //同时申请多个权限
            PermissionManager.getInstance(getApplicationContext()).execute(this,
                    Manifest.permission.RECORD_AUDIO,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE);

        } else {

            start_record.setEnabled(true);
        }

    }

    private boolean isRecordGotPermission() {

        return (ContextCompat.checkSelfPermission(mContext, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);

    }

    //如果有权限的话返回
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.getInstance(getApplicationContext()).
                onRequestPermissionsResult(requestCode, permissions, grantResults);

        Log.e(TAG, "recorder ~~~~~~~~~~~~~~onRequestPermissionsResult");

        start_record.setEnabled(true);

    }

    private long timeStartRecord;
    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.start_record:

                mediaPlayerTool.stop();

                record_status.setText(R.string.record_doing);

                start_record.setEnabled(false);
                stop_record.setEnabled(false);
                play_record.setEnabled(false);
                finish_record.setEnabled(false);


                myHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        stop_record.setEnabled(true);
                    }
                }, RECORD_MIN_TIME + 1000);

                //开始录音，并将录音数据写入到指定的文件中
                if(!isRecording){
                    isRecording = true;

                    startRecord();

                    timeStartRecord = System.currentTimeMillis();

                    Toast.makeText(mContext, R.string.record_start, Toast.LENGTH_SHORT).show();

                }
                break;
            case R.id.stop_record:

                mediaPlayerTool.stop();

                finish_record.setEnabled(false);
                start_record.setEnabled(true);
                stop_record.setEnabled(false);
                play_record.setEnabled(false);


                record_status.setText(R.string.record_not_doing);
                isRecording=false;
                //停止录音
                stopRecord();

                final long timeStopRecord = System.currentTimeMillis();

                Log.e(TAG, "timeStartRecord = " + timeStartRecord + ", timeStopRecord = " + timeStopRecord);
                if (!isPcba && timeStopRecord - timeStartRecord < RECORD_MIN_TIME) {
                    finish_record.setEnabled(false);
                    Toast.makeText(mContext, getResources().getString(R.string.below_min_time), Toast.LENGTH_LONG).show();

                } else {

                    play_record.setEnabled(true);

                    Toast.makeText(mContext, R.string.record_stop, Toast.LENGTH_SHORT).show();
                }

                break;
            case R.id.play_record:

                play_record.setEnabled(false);
                start_record.setEnabled(false);
                stop_record.setEnabled(false);
                finish_record.setEnabled(false);

                //播放指定的录音文件
                requestAudioFocus();
                mediaPlayerTool.stop();
                mediaPlayerTool.playPcm(RECORDER_FILE_PATH);


                myHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        finish_record.setEnabled(true);
                        start_record.setEnabled(true);
                        stop_record.setEnabled(false);
                    }
                }, RECORD_MIN_TIME + 1000);
                break;
            case R.id.finish_record:

                mediaPlayerTool.stop();
                try {
                    File file = new File(RECORDER_FILE_PATH);
                    if (file.exists()) {
                        file.delete();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                showDialog();
                break;
            default:
                break;
        }
    }

    private void showDialog() {

        final String title = getString(R.string.record_test);
        final String msg = getString(R.string.item_exit_test);
        ViewDialogFragment dialog = ViewDialogFragment.newInstance(title, msg);

        dialog.show(getFragmentManager(),
                new ViewDialogFragment.Callback() {
                    @Override
                    public void onClick() {

                        Toast.makeText(mContext, R.string.test_ok, Toast.LENGTH_SHORT).show();
                        setResult(RESULT_OK);
                        ActivityCompat.finishAfterTransition(RecorderActivity.this);

                    }
                },
                new ViewDialogFragment.Callback() {
                    @Override
                    public void onClick() {

                        Toast.makeText(mContext, R.string.test_fail, Toast.LENGTH_SHORT).show();
                        setResult(RESULT_CANCELED);
                        ActivityCompat.finishAfterTransition(RecorderActivity.this);
                    }
                });

    }


    private void requestAudioFocus(){
        if(null == mAudioManager){
            mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);// 获取声音管理器
        }
        mAudioManager.requestAudioFocus(mAudioFocusListener,
                AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
    }

    /**
     * 音频焦点事件监听器
     */
    private AudioManager.OnAudioFocusChangeListener mAudioFocusListener = new AudioManager.OnAudioFocusChangeListener() {
        public void onAudioFocusChange(int focusChange) {

        }
    };


    private void startRecord() {
        new Thread(new Runnable(){
            @Override
            public void run() {
                RecorderOperator.getInstance().setRecordPath(RECORDER_FILE_PATH);
                RecorderOperator.getInstance().startRecord();
            }}).start();
    }

    private void stopRecord() {

        RecorderOperator.getInstance().stopRecord();

    }

    private BroadcastReceiver headsetPlugReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();

            if (action != null && action.equals(Intent.ACTION_HEADSET_PLUG)) {
                if (intent.hasExtra("state")) {

                    boolean unplug = (intent.getIntExtra("state", 0) == 0);
                    Log.e(TAG, "unplug = " + unplug);

                    if (unplug){

                        showDialogWhenHeadsetUnplug();

                    } else {

                        dismissDialogWhenHeadsetUnplug();
                    }
                }
            }
        }
    };

    ViewDialogFragment dialogWhenHeadsetUnplug;

    private void dismissDialogWhenHeadsetUnplug() {

        if (dialogWhenHeadsetUnplug != null) {
            dialogWhenHeadsetUnplug.dismiss();
            dialogWhenHeadsetUnplug = null;
        }
    }

    private void showDialogWhenHeadsetUnplug() {

        if (dialogWhenHeadsetUnplug == null) {
            final String title = getString(R.string.headset_event);
            final String msg = getString(R.string.headset_unplug);
            dialogWhenHeadsetUnplug = ViewDialogFragment.newInstance(title, msg, false);
        }

        if (!dialogWhenHeadsetUnplug.isShowing()) {
            dialogWhenHeadsetUnplug.show(getFragmentManager());
        }
    }

    private static final class MyHandler extends Handler {
        private final WeakReference<RecorderActivity> reference;

        public MyHandler(RecorderActivity activity) {
            reference = new WeakReference<RecorderActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {

            RecorderActivity activity = reference.get();
            if (activity == null) {
                return;
            }

            final int what = msg.what;

            switch (what) {
                case MediaPlayerTool.EVENT_PLAY_OVER:
                    activity.play_record.setEnabled(true);
                    break;
            }
        }
    }

}
